<template>
  <div class="carousel" @mouseenter="showControls = true" @mouseleave="showControls = false">
    <!-- 轮播图片 -->
    <img
        v-for="(image, index) in images"
        :key="index"
        :src="image"
        :alt="`Carousel Image ${index + 1}`"
        :class="{ active: currentIndex === index }"
        @error="handleImageError"
    />
    <!-- 手动切换按钮 -->
    <div class="controls" v-show="showControls">
      <button @click="prevImage"><</button>
      <button @click="nextImage">></button>
    </div>
    <!-- 指示器 -->
    <div class="indicators">
      <span
          v-for="(image, index) in images"
          :key="index"
          :class="{ active: currentIndex === index }"
          @click="currentIndex = index"
      ></span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

// 导入图片
import img1 from '@/assets/img/banner/banner1.jpeg';
import img2 from '@/assets/img/banner/banner2.jpeg';
import img3 from '@/assets/img/banner/banner3.jpeg';
import img4 from '@/assets/img/banner/banner4.jpeg';

// 定义轮播图图片数组
const images = ref([img1, img2, img3, img4]);

// 当前显示的图片索引
const currentIndex = ref(0);

// 定时器 ID
let timer;

// 控制按钮是否显示
const showControls = ref(false);

// 切换到下一张图片的函数
const nextImage = () => {
  currentIndex.value = (currentIndex.value + 1) % images.value.length;
};

// 切换到上一张图片的函数
const prevImage = () => {
  currentIndex.value = (currentIndex.value - 1 + images.value.length) % images.value.length;
};

// 组件挂载时启动定时器
onMounted(() => {
  timer = setInterval(nextImage, 3000);
});

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  clearInterval(timer);
});

// 处理图片加载失败事件
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
};
</script>

<style scoped>
.carousel {
  width: 100%;
  height: 520px;
  overflow: hidden;
  position: relative;
  margin-top: 60px; /* 假设导航栏高度为 40px，根据实际情况调整 */
}

.carousel img {
  width: 100%;
  height: 520px;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.carousel img.active {
  opacity: 1;
}

.controls {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 1200px; /* 设置宽度为 1200px */
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: space-between;
  z-index: 1;
}

.controls button {
  padding: 10px 15px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  cursor: pointer;
  font-size: 20px;
}

.indicators {
  position: absolute;
  bottom: 50px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
}

.indicators span {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  margin: 0 5px;
  cursor: pointer;
}

.indicators span.active {
  background-color: white;
}
</style>